package model

import (
	"time"
)

// SystemConfig 系统配置
type SystemConfig struct {
	ID           string                 `json:"id" bson:"_id"`
	Key          string                 `json:"key" bson:"key"`
	Value        interface{}            `json:"value" bson:"value"`
	Description  string                 `json:"description" bson:"description"`
	Type         string                 `json:"type" bson:"type"` // string, number, boolean, object, array
	Category     string                 `json:"category" bson:"category"`
	IsEncrypted  bool                   `json:"is_encrypted" bson:"is_encrypted"`
	IsSystemOnly bool                   `json:"is_system_only" bson:"is_system_only"`
	Required     bool                   `json:"required" bson:"required"`
	DefaultValue interface{}            `json:"default_value" bson:"default_value"`
	Validation   map[string]interface{} `json:"validation" bson:"validation"`
	CreatedAt    time.Time              `json:"created_at" bson:"created_at"`
	UpdatedAt    time.Time              `json:"updated_at" bson:"updated_at"`
	UpdatedBy    string                 `json:"updated_by" bson:"updated_by"`
}

// ConfigCategory 配置分类常量
const (
	ConfigCategorySystem   = "system"    // 系统配置
	ConfigCategoryCall     = "call"      // 呼叫配置
	ConfigCategoryACD      = "acd"       // ACD配置
	ConfigCategoryQueue    = "queue"     // 队列配置
	ConfigCategoryRecording = "recording" // 录音配置
	ConfigCategoryTicket   = "ticket"    // 工单配置
	ConfigCategoryMonitor  = "monitor"   // 监控配置
	ConfigCategorySecurity = "security"  // 安全配置
)

// ConfigType 配置类型常量
const (
	ConfigTypeString  = "string"
	ConfigTypeNumber  = "number"
	ConfigTypeBoolean = "boolean"
	ConfigTypeObject  = "object"
	ConfigTypeArray   = "array"
)

// UserRole 用户角色
type UserRole struct {
	ID          string    `json:"id" bson:"_id"`
	Name        string    `json:"name" bson:"name"`
	Description string    `json:"description" bson:"description"`
	Permissions []string  `json:"permissions" bson:"permissions"`
	IsDefault   bool      `json:"is_default" bson:"is_default"`
	IsSystem    bool      `json:"is_system" bson:"is_system"`
	CreatedAt   time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" bson:"updated_at"`
}

// User 用户模型
type User struct {
	ID        string    `json:"id" bson:"_id"`
	Username  string    `json:"username" bson:"username"`
	Password  string    `json:"-" bson:"password"` // 密码不返回给客户端
	Email     string    `json:"email" bson:"email"`
	FullName  string    `json:"full_name" bson:"full_name"`
	Phone     string    `json:"phone" bson:"phone"`
	RoleID    string    `json:"role_id" bson:"role_id"`
	Status    string    `json:"status" bson:"status"` // active, inactive, locked
	AgentID   string    `json:"agent_id,omitempty" bson:"agent_id,omitempty"`
	LastLogin time.Time `json:"last_login" bson:"last_login"`
	CreatedAt time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}

// UserStatus 用户状态常量
const (
	UserStatusActive   = "active"
	UserStatusInactive = "inactive"
	UserStatusLocked   = "locked"
)

// Permission 权限
type Permission struct {
	ID          string    `json:"id" bson:"_id"`
	Code        string    `json:"code" bson:"code"`
	Name        string    `json:"name" bson:"name"`
	Description string    `json:"description" bson:"description"`
	Category    string    `json:"category" bson:"category"`
	CreatedAt   time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" bson:"updated_at"`
}

// PermissionCategory 权限分类常量
const (
	PermissionCategorySystem   = "system"    // 系统管理
	PermissionCategoryAgent    = "agent"     // 座席管理
	PermissionCategoryCall     = "call"      // 呼叫管理
	PermissionCategoryQueue    = "queue"     // 队列管理
	PermissionCategoryIVR      = "ivr"       // IVR管理
	PermissionCategoryRecording = "recording" // 录音管理
	PermissionCategoryQuality  = "quality"   // 质检管理
	PermissionCategoryTicket   = "ticket"    // 工单管理
	PermissionCategoryMonitor  = "monitor"   // 监控管理
)

// LoginRequest 登录请求
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// LoginResponse 登录响应
type LoginResponse struct {
	Token    string `json:"token"`
	User     User   `json:"user"`
	ExpiresIn int64 `json:"expires_in"`
}

// ChangePasswordRequest 修改密码请求
type ChangePasswordRequest struct {
	OldPassword string `json:"old_password" binding:"required"`
	NewPassword string `json:"new_password" binding:"required,min=6"`
}

// ResetPasswordRequest 重置密码请求
type ResetPasswordRequest struct {
	Username string `json:"username" binding:"required"`
}

// CreateUserRequest 创建用户请求
type CreateUserRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required,min=6"`
	Email    string `json:"email" binding:"required,email"`
	FullName string `json:"full_name" binding:"required"`
	Phone    string `json:"phone"`
	RoleID   string `json:"role_id" binding:"required"`
	AgentID  string `json:"agent_id,omitempty"`
}

// UpdateUserRequest 更新用户请求
type UpdateUserRequest struct {
	Email    string `json:"email" binding:"omitempty,email"`
	FullName string `json:"full_name"`
	Phone    string `json:"phone"`
	RoleID   string `json:"role_id"`
	Status   string `json:"status"`
	AgentID  string `json:"agent_id,omitempty"`
}

// UpdateSystemConfigRequest 更新系统配置请求
type UpdateSystemConfigRequest struct {
	Value     interface{}            `json:"value" binding:"required"`
	UpdatedBy string                 `json:"updated_by" binding:"required"`
}

// BatchUpdateSystemConfigRequest 批量更新系统配置请求
type BatchUpdateSystemConfigRequest struct {
	Configs   []SystemConfigUpdateItem `json:"configs" binding:"required"`
	UpdatedBy string                   `json:"updated_by" binding:"required"`
}

// SystemConfigUpdateItem 系统配置更新项
type SystemConfigUpdateItem struct {
	Key   string      `json:"key" binding:"required"`
	Value interface{} `json:"value" binding:"required"`
}

// CreateRoleRequest 创建角色请求
type CreateRoleRequest struct {
	Name        string   `json:"name" binding:"required"`
	Description string   `json:"description"`
	Permissions []string `json:"permissions" binding:"required"`
	IsDefault   bool     `json:"is_default"`
}

// UpdateRoleRequest 更新角色请求
type UpdateRoleRequest struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Permissions []string `json:"permissions"`
	IsDefault   bool     `json:"is_default"`
}

// Role 角色模型
type Role struct {
	ID          string    `json:"id" bson:"_id"`
	Name        string    `json:"name" bson:"name"`
	Description string    `json:"description" bson:"description"`
	Permissions []string  `json:"permissions" bson:"permissions"`
	IsDefault   bool      `json:"is_default" bson:"is_default"`
	CreatedAt   time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" bson:"updated_at"`
}

// AuditLog 审计日志
type AuditLog struct {
	ID          string                 `json:"id" bson:"_id"`
	UserID      string                 `json:"user_id" bson:"user_id"`
	Username    string                 `json:"username" bson:"username"`
	Action      string                 `json:"action" bson:"action"`
	Module      string                 `json:"module" bson:"module"`
	TargetID    string                 `json:"target_id" bson:"target_id"`
	TargetType  string                 `json:"target_type" bson:"target_type"`
	Details     map[string]interface{} `json:"details" bson:"details"`
	IPAddress   string                 `json:"ip_address" bson:"ip_address"`
	UserAgent   string                 `json:"user_agent" bson:"user_agent"`
	Status      string                 `json:"status" bson:"status"` // success, fail
	Error       string                 `json:"error,omitempty" bson:"error,omitempty"`
	CreatedAt   time.Time              `json:"created_at" bson:"created_at"`
}

// AuditLogQuery 审计日志查询参数
type AuditLogQuery struct {
	UserID     string    `form:"user_id"`
	Module     string    `form:"module"`
	Action     string    `form:"action"`
	TargetID   string    `form:"target_id"`
	TargetType string    `form:"target_type"`
	Status     string    `form:"status"`
	StartDate  time.Time `form:"start_date"`
	EndDate    time.Time `form:"end_date"`
	Limit      int       `form:"limit,default=100"`
	Offset     int       `form:"offset,default=0"`
	SortBy     string    `form:"sort_by,default=created_at"`
	SortOrder  string    `form:"sort_order,default=desc"`
}

// PasswordPolicy 密码策略
type PasswordPolicy struct {
	MinLength      int  `json:"min_length" bson:"min_length"`
	MaxLength      int  `json:"max_length" bson:"max_length"`
	RequireUppercase bool `json:"require_uppercase" bson:"require_uppercase"`
	RequireLowercase bool `json:"require_lowercase" bson:"require_lowercase"`
	RequireNumber  bool `json:"require_number" bson:"require_number"`
	RequireSpecial bool `json:"require_special" bson:"require_special"`
	HistoryCount   int  `json:"history_count" bson:"history_count"`
	ExpirationDays int  `json:"expiration_days" bson:"expiration_days"`
	LockoutAttempts int `json:"lockout_attempts" bson:"lockout_attempts"`
	LockoutMinutes int  `json:"lockout_minutes" bson:"lockout_minutes"`
}

// APIKey API密钥
type APIKey struct {
	ID          string    `json:"id" bson:"_id"`
	UserID      string    `json:"user_id" bson:"user_id"`
	Key         string    `json:"key" bson:"key"`
	Name        string    `json:"name" bson:"name"`
	Description string    `json:"description" bson:"description"`
	Permissions []string  `json:"permissions" bson:"permissions"`
	Status      string    `json:"status" bson:"status"` // active, revoked
	ExpiresAt   time.Time `json:"expires_at" bson:"expires_at"`
	CreatedAt   time.Time `json:"created_at" bson:"created_at"`
	LastUsedAt  time.Time `json:"last_used_at" bson:"last_used_at"`
}

// APIKeyStatus API密钥状态常量
const (
	APIKeyStatusActive  = "active"
	APIKeyStatusRevoked = "revoked"
)

// CreateAPIKeyRequest 创建API密钥请求
type CreateAPIKeyRequest struct {
	Name        string    `json:"name" binding:"required"`
	Description string    `json:"description"`
	Permissions []string  `json:"permissions" binding:"required"`
	ExpiresAt   time.Time `json:"expires_at"`
}

// SecuritySettings 安全设置
type SecuritySettings struct {
	Enable2FA              bool           `json:"enable_2fa" bson:"enable_2fa"`
	PasswordPolicy         PasswordPolicy `json:"password_policy" bson:"password_policy"`
	SessionTimeoutMinutes  int            `json:"session_timeout_minutes" bson:"session_timeout_minutes"`
	MaxConcurrentSessions  int            `json:"max_concurrent_sessions" bson:"max_concurrent_sessions"`
	AllowedIPs             []string       `json:"allowed_ips" bson:"allowed_ips"`
	BlockFailedAttempts    bool           `json:"block_failed_attempts" bson:"block_failed_attempts"`
	EnableAuditLogging     bool           `json:"enable_audit_logging" bson:"enable_audit_logging"`
	DataRetentionDays      int            `json:"data_retention_days" bson:"data_retention_days"`
	EncryptionEnabled      bool           `json:"encryption_enabled" bson:"encryption_enabled"`
}

// EmailTemplate 邮件模板
type EmailTemplate struct {
	ID          string    `json:"id" bson:"_id"`
	Code        string    `json:"code" bson:"code"`
	Name        string    `json:"name" bson:"name"`
	Subject     string    `json:"subject" bson:"subject"`
	Body        string    `json:"body" bson:"body"`
	IsHTML      bool      `json:"is_html" bson:"is_html"`
	Variables   []string  `json:"variables" bson:"variables"`
	CreatedAt   time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" bson:"updated_at"`
}

// SMTPConfig SMTP配置
type SMTPConfig struct {
	Host          string `json:"host" bson:"host"`
	Port          int    `json:"port" bson:"port"`
	Username      string `json:"username" bson:"username"`
	Password      string `json:"-" bson:"password"` // 密码不返回给客户端
	FromEmail     string `json:"from_email" bson:"from_email"`
	FromName      string `json:"from_name" bson:"from_name"`
	UseSSL        bool   `json:"use_ssl" bson:"use_ssl"`
	UseTLS        bool   `json:"use_tls" bson:"use_tls"`
	Timeout       int    `json:"timeout" bson:"timeout"` // 超时时间（秒）
	MaxRetries    int    `json:"max_retries" bson:"max_retries"`
}

// NotificationChannel 通知渠道
type NotificationChannel struct {
	ID          string    `json:"id" bson:"_id"`
	Type        string    `json:"type" bson:"type"` // email, sms, webhook
	Name        string    `json:"name" bson:"name"`
	Description string    `json:"description" bson:"description"`
	Config      map[string]interface{} `json:"config" bson:"config"`
	Status      string    `json:"status" bson:"status"` // active, inactive
	CreatedAt   time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" bson:"updated_at"`
}

// NotificationChannelType 通知渠道类型常量
const (
	NotificationChannelTypeEmail  = "email"
	NotificationChannelTypeSMS    = "sms"
	NotificationChannelTypeWebhook = "webhook"
)

// NotificationTemplate 通知模板
type NotificationTemplate struct {
	ID            string    `json:"id" bson:"_id"`
	Event         string    `json:"event" bson:"event"`
	ChannelTypes  []string  `json:"channel_types" bson:"channel_types"`
	TitleTemplate string    `json:"title_template" bson:"title_template"`
	BodyTemplate  string    `json:"body_template" bson:"body_template"`
	Enabled       bool      `json:"enabled" bson:"enabled"`
	Recipients    []string  `json:"recipients" bson:"recipients"` // 默认接收者
	CreatedAt     time.Time `json:"created_at" bson:"created_at"`
	UpdatedAt     time.Time `json:"updated_at" bson:"updated_at"`
}

// NotificationEvent 通知事件常量
const (
	NotificationEventUserLoginFailure    = "user_login_failure"
	NotificationEventUserAccountLocked   = "user_account_locked"
	NotificationEventSystemWarning       = "system_warning"
	NotificationEventSystemError         = "system_error"
	NotificationEventAgentStatusChange   = "agent_status_change"
	NotificationEventQueueThresholdAlert = "queue_threshold_alert"
	NotificationEventNewTicket           = "new_ticket"
	NotificationEventTicketAssigned      = "ticket_assigned"
	NotificationEventTicketUpdated       = "ticket_updated"
)

// BackupConfig 备份配置
type BackupConfig struct {
	Enabled           bool      `json:"enabled" bson:"enabled"`
	ScheduleType      string    `json:"schedule_type" bson:"schedule_type"` // daily, weekly, monthly
	ScheduleDay       int       `json:"schedule_day" bson:"schedule_day"`
	ScheduleHour      int       `json:"schedule_hour" bson:"schedule_hour"`
	RetentionDays     int       `json:"retention_days" bson:"retention_days"`
	IncludeDatabase   bool      `json:"include_database" bson:"include_database"`
	IncludeRecordings bool      `json:"include_recordings" bson:"include_recordings"`
	IncludeLogs       bool      `json:"include_logs" bson:"include_logs"`
	StoragePath       string    `json:"storage_path" bson:"storage_path"`
	LastBackupAt      time.Time `json:"last_backup_at" bson:"last_backup_at"`
	LastBackupStatus  string    `json:"last_backup_status" bson:"last_backup_status"` // success, fail
	LastBackupError   string    `json:"last_backup_error,omitempty" bson:"last_backup_error,omitempty"`
}

// BackupScheduleType 备份调度类型常量
const (
	BackupScheduleTypeDaily   = "daily"
	BackupScheduleTypeWeekly  = "weekly"
	BackupScheduleTypeMonthly = "monthly"
)